<template>
  <div id="commissionMonthDetailpage">
    <BreadcrumbComponent :breadcrumbItems="breadcrumbItems" />
    <a-space direction="vertical" style="width: 100%">
      <a-card title="佣金數據" :loading="detailLoading">
        <a-descriptions>
          <a-descriptions-item label="統計月份">{{
            detail.statMonth
          }}</a-descriptions-item>
          <a-descriptions-item label="員工編號">{{
            detail.staffCode
          }}</a-descriptions-item>
          <a-descriptions-item label="店鋪"
            >{{ detail.shop?.name }} ({{
              detail.shop?.code
            }})</a-descriptions-item
          >
          <a-descriptions-item label="醫師名稱">{{
            detail.doctor?.name
          }}</a-descriptions-item>
          <a-descriptions-item label="醫師類別">
            <a-tag v-if="detail.doctor?.staffType === 1" type="info"
              >合作醫師</a-tag
            >
            <a-tag v-else-if="detail.doctor?.staffType === 2" type="info"
              >員工</a-tag
            >
            <a-tag v-else type="info">未知</a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="診症佣金">
            ${{ Number(detail.consultCommission).toLocaleString() }}
          </a-descriptions-item>
          <a-descriptions-item label="附加項目佣金">
            $ {{ Number(detail.additionalCommission).toLocaleString() }}
          </a-descriptions-item>
          <a-descriptions-item label="常規銷售佣金">
            $ {{ Number(detail.regularCommission).toLocaleString() }}
          </a-descriptions-item>

          <a-descriptions-item label="本廠銷售佣金">
            $ {{ Number(detail.extraCommission).toLocaleString() }}
          </a-descriptions-item>

          <a-descriptions-item label="總佣金">
            <template v-if="isDoctor && !detail.isArchived">待計算</template>
            <template v-else
              >$ {{ Number(detail.totalCommission).toLocaleString() }}</template
            >
          </a-descriptions-item>
          <a-descriptions-item label="開始日期">{{
            detail.startDate
          }}</a-descriptions-item>
          <a-descriptions-item label="結束日期">{{
            detail.endDate
          }}</a-descriptions-item>
          <a-descriptions-item label="是否歸檔">
            <a-tag
              :bordered="false"
              color="success"
              v-if="detail.isArchived == true"
              >已歸檔</a-tag
            >
            <a-tag :bordered="false" color="processing" v-else>未歸檔</a-tag>
          </a-descriptions-item>
        </a-descriptions>
      </a-card>

      <a-card
        title="診金分成統計"
        :loading="detailLoading"
        v-if="detail.consultCommStats.length > 0"
      >
        <a-table
          :columns="consultCommStatcolumns"
          :data-source="detail.consultCommStats"
          :loading="loading"
          :pagination="{pageSize:5,showTotal: (total: number) => `共 ${total} 條記錄`,}"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'class'">
              <a-tag color="#f50" v-if="record.class == 1">推廣活動</a-tag>
              <a-tag color="#2db7f5" v-else-if="record.class == 2"
                >自定義診金類型</a-tag
              >
              <a-tag color="#87d068" v-else-if="record.class == 3"
                >指定服務</a-tag
              >
              <a-tag color="#108ee9" v-else>默認</a-tag>
            </template>
            <template v-if="column.dataIndex === 'useCode'">
              <span v-if="record.useCode">{{ record.useCode }}</span>
              <a-tag color="default" v-else>none</a-tag>
            </template>
            <template v-if="column.dataIndex === 'shareAmount'">
              $ {{ Number(record.shareAmount).toLocaleString() }}
            </template>
            <template v-if="column.key === 'action'">
              <a-button @click="viewReateList('consult', record)" shape="round"
                >關聯發票</a-button
              >
            </template>
          </template>
        </a-table>
      </a-card>
      <a-card
        title="附加項目分成統計"
        :loading="detailLoading"
        v-if="detail.additionalCommStats.length > 0"
      >
        <a-table
          :columns="additionalCommStatcolumns"
          :data-source="detail.additionalCommStats"
          :loading="loading"
          :pagination="{pageSize:5,showTotal: (total: number) => `共 ${total} 條記錄`,}"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'type'">
              <a-tag color="#f50" v-if="record.type == 1">套票</a-tag>
              <a-tag color="#2db7f5" v-else-if="record.type == 2">針灸</a-tag>
              <a-tag color="#87d068" v-else-if="record.type == 3">天灸</a-tag>
              <a-tag color="#108ee9" v-else>未知</a-tag>
            </template>
            <template v-if="column.dataIndex === 'shareType'">
              <a-tag color="#f50" v-if="record.shareType == 1">固定金額</a-tag>
              <a-tag color="#2db7f5" v-else-if="record.shareType == 2"
                >比例</a-tag
              >
              <a-tag color="#108ee9" v-else>未知</a-tag>
            </template>

            <template v-if="column.dataIndex === 'shareValue'">
              <span v-if="record.shareType == 1">$</span>
              {{ record.shareValue }}
              <span v-if="record.shareType == 2">%</span>
            </template>

            <template v-if="column.dataIndex === 'amount'">
              $ {{ Number(record.amount).toLocaleString() }}
            </template>

            <template v-if="column.dataIndex === 'commission'">
              $ {{ Number(record.commission).toLocaleString() }}
            </template>
            <template v-if="column.key === 'action'">
              <a-button
                @click="viewReateList('additional', record)"
                shape="round"
                >關聯發票</a-button
              >
            </template>
          </template>
        </a-table>
      </a-card>
      <a-card
        title="常規銷售分成統計"
        :loading="detailLoading"
        v-if="detail.regularCommStats.length > 0"
      >
        <a-table
          :columns="regularCommStatcolumns"
          :data-source="detail.regularCommStats"
          :loading="loading"
          :pagination="{pageSize:5,showTotal: (total: number) => `共 ${total} 條記錄`,}"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'type'">
              <a-tag color="#f50" v-if="record.type == 1">處方</a-tag>
              <a-tag color="#2db7f5" v-else-if="record.type == 2">蟲草</a-tag>
              <a-tag color="#87d068" v-else-if="record.type == 3">燕窩</a-tag>
              <a-tag color="#108ee9" v-else>總金額</a-tag>
            </template>
            <template v-if="column.dataIndex === 'shiftType'">
              <a-tag color="#f50" v-if="record.shiftType == 1">全日</a-tag>
              <a-tag color="#2db7f5" v-else-if="record.shiftType == 2"
                >半日</a-tag
              >
              <a-tag color="#108ee9" v-else>未知</a-tag>
            </template>
            <template v-if="column.dataIndex === 'ratio'">
              {{ ((record.commission / record.amount) * 100).toFixed(2) }}%
            </template>

            <template v-if="column.dataIndex === 'amount'">
              $ {{ Number(record.amount).toLocaleString() }}
            </template>

            <template v-if="column.dataIndex === 'commission'">
              $ {{ Number(record.commission).toLocaleString() }}
            </template>
            <template v-if="column.key === 'action'">
              <a-button @click="viewReateList('regular', record)" shape="round"
                >關聯發票</a-button
              >
            </template>
          </template>
        </a-table>
      </a-card>
      <a-card
        title="附加推廣分成統計"
        :loading="detailLoading"
        v-if="detail.extraCommStats.length > 0"
      >
        <a-table
          :columns="extraCommStatcolumns"
          :data-source="detail.extraCommStats"
          :loading="loading"
          :pagination="{pageSize:5,showTotal: (total: number) => `共 ${total} 條記錄`,}"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'type'">
              <a-tag color="#f50" v-if="record.type == 1">安宮系列</a-tag>
              <a-tag color="#2db7f5" v-else-if="record.type == 2"
                >位元堂本廠</a-tag
              >
              <a-tag color="#87d068" v-else-if="record.type == 3">OEM</a-tag>
              <a-tag color="#108ee9" v-else>總金額</a-tag>
            </template>
            <template v-if="column.dataIndex === 'ratio'">
              <span v-if="record.commission > 0">
                {{ ((record.commission / record.amount) * 100).toFixed(2) }}%
              </span>
            </template>

            <template v-if="column.dataIndex === 'amount'">
              $ {{ Number(record.amount).toLocaleString() }}
            </template>

            <template v-if="column.dataIndex === 'commission'">
              $ {{ Number(record.commission).toLocaleString() }}
            </template>
            <template v-if="column.key === 'action'">
              <a-button @click="viewReateList('extra', record)" shape="round"
                >關聯發票</a-button
              >
            </template>
          </template>
        </a-table>
      </a-card>

      <BackButton />
    </a-space>
  </div>
</template>
<script lang="ts" setup>
import { ref, onMounted, reactive } from "vue";
import BreadcrumbComponent from "@/components/BreadcrumbComponent.vue";
import { createPagination } from "@/utils/pagination";
import { commissionApi } from "@/api";
import { useRouter, useRoute } from "vue-router";
import { watchRouteQuery } from "@/utils/routeQueryWatcherUtil";
import BackButton from "@/components/BackButton.vue";
import { useAuthUserStore } from "@/store/authUserStore";
const route = useRoute();
const router = useRouter();
const breadcrumbItems = [
  { url: "/commission", name: "佣金管理" },
  { url: "", name: "佣金明細" },
];
const userInfo = useAuthUserStore().userInfo;
const isDoctor = userInfo.roles.includes("Doctor");

const loading = ref(false);
const tableData = ref([]);
const pagination = createPagination({ useRoute: false });
const detail = reactive({
  shopId: "",
  shop: { code: "", name: "" },
  staffCode: "",
  doctor: { name: "", staffType: 1 },
  shiftType: 0,
  staffType: 0,
  statMonth: "",
  totalCommission: 0,
  consultCommission: 0,
  additionalCommission: 0,
  regularCommission: 0,
  extraCommission: 0,
  consultCommStats: [],
  additionalCommStats: [],
  regularCommStats: [],
  extraCommStats: [],
  startDate: "",
  endDate: "",
  isArchived: false,
});

const detailLoading = ref(false);
const fetchDetail = async () => {
  try {
    detailLoading.value = true;
    const { data } = await commissionApi.getCommissionDetail(
      Number(route.params.id)
    );
    Object.assign(detail, data);
  } catch (error) {
    console.error("獲取詳情失敗", error);
  } finally {
    detailLoading.value = false;
  }
};

const consultCommStatcolumns = [
  {
    title: "歸屬大類",
    dataIndex: "class",
  },
  {
    title: "使用Code",
    dataIndex: "useCode",
  },
  {
    title: "診症數",
    dataIndex: "consultCount",
  },
  {
    title: "診症佣金",
    dataIndex: "shareAmount",
  },
  {
    title: "操作",
    key: "action",
  },
];

const additionalCommStatcolumns = [
  {
    title: "類型",
    dataIndex: "type",
  },
  {
    title: "分成方式",
    dataIndex: "shareType",
  },
  {
    title: "分成數值",
    dataIndex: "shareValue",
  },
  {
    title: "數量",
    dataIndex: "count",
  },
  {
    title: "銷售金額",
    dataIndex: "amount",
  },
  {
    title: "佣金",
    dataIndex: "commission",
  },
  {
    title: "操作",
    key: "action",
  },
];
const regularCommStatcolumns = [
  {
    title: "類型",
    dataIndex: "type",
  },
  {
    title: "駐診類型",
    dataIndex: "shiftType",
  },
  {
    title: "銷售金額",
    dataIndex: "amount",
  },
  {
    title: "比例",
    dataIndex: "ratio",
  },
  {
    title: "佣金",
    dataIndex: "commission",
  },
  {
    title: "操作",
    key: "action",
  },
];

const extraCommStatcolumns = [
  {
    title: "類型",
    dataIndex: "type",
  },
  {
    title: "銷售金額",
    dataIndex: "amount",
  },
  {
    title: "比例",
    dataIndex: "ratio",
  },
  {
    title: "佣金",
    dataIndex: "commission",
  },
  {
    title: "操作",
    key: "action",
  },
];

// 初始化加載
onMounted(() => {
  fetchDetail();
});

const viewReateList = (part: string, record) => {
  let params = {
    shop_id: detail.shopId,
    staff_code: detail.staffCode,
    inv_date_start: detail.startDate,
    inv_date_end: detail.endDate,
  };
  if (part == "consult") {
    router.push({
      name: "Invoice",
      query: {
        consult_share_class: record.class,
        use_code: record.useCode || "none",
        ...params,
      },
    });
  } else if (part == "additional") {
    router.push({
      name: "Invoice",
      query: {
        additional_type: record.type,
        ...params,
      },
    });
  } else if (part == "regular") {
    router.push({
      name: "Invoice",
      query: {
        regular_type: record.type,
        shift_type: record.shiftType,
        ...params,
      },
    });
  } else if (part == "extra") {
    router.push({
      name: "Invoice",
      query: {
        extra_type: record.type,
        ...params,
      },
    });
  }
};
</script>
<style scoped>
/* 組件樣式 */
</style>
